<script setup lang="ts">
import { h, ref, reactive, onMounted, onDeactivated } from "vue"
import {
  FormInst,
  useMessage,
  NButton,
  NForm,
  NFormItem,
  NInput,
  NDataTable,
  NInputNumber,
  NPopselect,
  NDrawer,
  NDrawerContent,
  NImage,
  NDivider,
  NCard,
  NSelect,
  NTag,
} from "naive-ui"
import { getIndentList, updateIndent, deliveryAdmin, getAdminList } from "@api/index"
import pagination from "@/components/pagination.vue"
import { getStorage } from "@/util/cache"
const orgId = getStorage("orgId")
const formRef = ref<FormInst | null>(null)
const message = useMessage()
const showDrawer = ref<boolean>(false)
let detailData = reactive({
  list: [],
  remark: "",
  prices: 0,
  detailedAddress: "",
  consigneePhone: "",
})

const bodyWidth = document.body.clientWidth
// onMounted(() => {
//   //组件挂载时的生命周期执行的方法
//   window.setInterval(function logname() {
//     // 其他定时执行的方法
//     handleGetIndentList({ limit: pageConfig.value.pageSize, page: pageConfig.value.page })
//   }, 10000);
// })

const formValue = ref({
  indentCode: "",
  userName: "",
  phonenumber: null,
  oneSite: null,
  twoSite: null,
  threeSite: null,
})
const pageConfig = ref({
  page: 1,
  pageSize: 10,
})
const pageTotal = ref(0)
const statusOptions = [
  {
    label: "已取消",
    value: 0,
  },
  {
    label: "待付款",
    value: 1,
    disabled: true,
  },
  {
    label: "进行中",
    value: 2,
    disabled: true,
  },
  {
    label: "完成",
    value: 3,
  },
  {
    label: "退款中",
    value: 4,
    disabled: true,
  },
  {
    label: "已退款",
    value: 5,
  },
]

const getTagType = (type: number) => {
  if (type === 0) {
    return ""
  }
  if (type === 1) {
    return "warning"
  }
  if (type === 2) {
    return "info"
  }
  if (type === 3) {
    return "success"
  }
}

const getSelftype = (type: number) => {
  if (type === 1) {
    return "success"
  }
  if (type === 2) {
    return ""
  }
}

const columns = [
  {
    title: "订单Code",
    key: "indentCode",
  },
  {
    title: "用户ID",
    key: "userId",
  },
  {
    title: "下单客户姓名",
    key: "userName",
    render(row: any) {
      return `${row.userName ? row.userName : "-"}`
    },
  },
  {
    title: "下单客户联系电话",
    key: "phonenumber",
  },
  {
    title: "地址(楼栋)",
    key: "detailedAddress",
    // render(row: any) {
    //   return `${row.shopAddress[0].oneSite}-${row.shopAddress[0].twoSite}-${row.shopAddress[0].threeSite}`
    // },
  },
  {
    title: "订单状态",
    key: "indentStatus",
    render(row: any) {
      return [
        h(
          NTag,
          {
            type: getTagType(row.indentStatus),
          },
          {
            default: () => statusOptions.find((item: any) => row.indentStatus === item.value).label,
          }
        ),
      ]
    },
  },
  {
    title: "是否自提",
    key: "oneself",
    render(row: any) {
      return [
        h(
          NTag,
          {
            type: getSelftype(row.oneself),
          },
          {
            default: () => row.oneself == 1 ? '配送' : '自提',
          }
        ),
      ]
    },
  },
  {
    title: "订单金额",
    key: "prices",
  },
  {
    title: "配送费",
    key: "deliveryPrices",
  },
  {
    title: "利润额",
    key: "profit",
  },
  {
    title: "管理员",
    key: "adminId",
    render(row: any) {
      return [
        h(NSelect, {
          value: row.adminId,
          options: adminList.data,
          onUpdateValue: (value: any) =>
            handleChangeAdmin({ indentId: row.indentId, adminId: value }),
        }),
      ]
    },
  },
  {
    title: "创建时间",
    key: "createTime",
  },
  {
    title: "操作",
    key: "action",
    render(row: any) {
      return [
        h(
          NButton,
          {
            size: "small",
            onClick: () => {
              showDrawer.value = true
              detailData.list = row.goodsVOList
              detailData.remark = row.remark
              detailData.prices = row.prices
              detailData.detailedAddress = row.detailedAddress
              detailData.consigneePhone = row.consigneePhone
            },
          },
          { default: () => "订单详情" }
        ),
        h(
          NPopselect,
          {
            options: statusOptions,
            trigger: "click",
            size: "small",
            onUpdateValue: (value: number) => {
              handleIndentStatus({ indentStatus: value, indentId: row.indentId })
            },
          },
          { default: () => "修改状态" }
        ),
      ]
    },
  },
]

const phoneCloumns = [
  // {
  //   title: "订单Code",
  //   key: "indentCode",
  //   width: 120,
  // },
  {
    title: "用户ID",
    key: "userId",
  },
  {
    title: "客户名",
    key: "userName",
    render(row: any) {
      return `${row.userName ? row.userName : "-"}`
    },
    width: 100,
  },
  {
    title: "订单状态",
    key: "indentStatus",
    render(row: any) {
      return [
        h(
          NTag,
          {
            type: getTagType(row.indentStatus),
          },
          {
            default: () => statusOptions.find((item: any) => row.indentStatus === item.value).label,
          }
        ),
      ]
    },
  },
  {
    title: "是否自提",
    key: "oneself",
    render(row: any) {
      return [
        h(
          NTag,
          {
            type: getSelftype(row.oneself),
          },
          {
            default: () => row.oneself == 1 ? '配送' : '自提',
          }
        ),
      ]
    },
  },
  {
    title: "管理员",
    key: "adminId",
    render(row: any) {
      return [
        h(NSelect, {
          value: row.adminId,
          options: adminList.data,
          onUpdateValue: (value: any) =>
            handleChangeAdmin({ indentId: row.indentId, adminId: value }),
        }),
      ]
    },
  },
  {
    title: "操作",
    key: "action",
    render(row: any) {
      return [
        h(
          NButton,
          {
            size: "small",
            onClick: () => {
              showDrawer.value = true
              detailData.list = row.goodsVOList
              detailData.remark = row.remark
              detailData.prices = row.prices
              detailData.detailedAddress = row.detailedAddress
              detailData.consigneePhone = row.consigneePhone
            },
          },
          { default: () => "订单详情" }
        ),
        h(
          NPopselect,
          {
            options: statusOptions,
            trigger: "click",
            size: "small",
            onUpdateValue: (value: number) => {
              handleIndentStatus({ indentStatus: value, indentId: row.indentId })
            },
          },
          { default: () => "修改状态" }
        ),
      ]
    },
  },
]

const indentsList: any = ref([])
const adminList: any = reactive({
  data: [],
})
const handleGetAdminList = () => {
  getAdminList({ orgId }).then((res: any) => {
    adminList.data = res.data.map((item: any) => {
      return { label: item.adminName, value: item.id }
    })
  })
}
handleGetAdminList()
const handleGetIndentList = (data: any) => {
  getIndentList({ ...data, orgId }).then((res: any) => {
    indentsList.value = res.data?.list
    pageTotal.value = res.data?.totalCount
  })
}

handleGetIndentList({
  limit: pageConfig.value.pageSize,
  page: pageConfig.value.page,
  ...formValue.value,
})

//分配管理员
const handleChangeAdmin = (data: any) => {
  deliveryAdmin(data).then((res: any) => {
    if (res.code === 200) {
      message.success(res.msg)
    } else {
      message.error(res.msg)
    }
    handleGetIndentList({
      limit: pageConfig.value.pageSize,
      page: pageConfig.value.page,
      ...formValue.value,
    })
  })
}

//搜索功能
const handleSearch = () => {
  formRef.value?.validate(errors => {
    if (!errors) {
      handleGetIndentList({ ...formValue.value, page: 1, limit: 10 })
    } else {
      console.log(errors)
    }
  })
}

//更新状态
const handleIndentStatus = (data: any) => {
 if(data.indentStatus == 0){
  if(!confirm("确定要取消订单吗？")) return
 } 

    updateIndent(data).then((res: any) => {
    if (res.code === 200) {
      message.success(res.msg)
    } else {
      message.error(res.msg)
    }
    handleGetIndentList({ limit: pageConfig.value.pageSize, page: pageConfig.value.page })
  })

}

//抽屉关闭时
const drawerClose = () => {
  showDrawer.value = false
  detailData = {
    list: [],
    remark: "",
    prices: 0,
    detailedAddress: "",
    consigneePhone: "",
  }
}

//分页
const handleChangePage = () => {
  handleGetIndentList({
    limit: pageConfig.value.pageSize,
    page: pageConfig.value.page,
    ...formValue.value,
  })
}
</script>

<template>
  <div class="wrapper">
    <div class="search">
      <n-form ref="formRef" :inline="bodyWidth < 600 ? false : true" :label-width="80" label-placement="left"
        :model="formValue">
        <n-form-item label="订单号:" path="indentCode">
          <n-input v-model:value="formValue.indentCode" placeholder="全部" clearable />
        </n-form-item>
        <n-form-item label="用户名:" path="userName">
          <n-input v-model:value="formValue.userName" placeholder="全部" clearable />
        </n-form-item>
        <n-form-item label="手机号:" path="phonenumber">
          <n-input v-model:value="formValue.phonenumber" placeholder="全部" clearable />
        </n-form-item>
        <n-form-item label="楼栋:" path="oneSite">
          <n-input-number v-model:value="formValue.oneSite" placeholder="栋" class="form_site" clearable />
        </n-form-item>
        <n-form-item :label="bodyWidth < 600 ? ' ' : ''" path="twoSite">
          <n-input-number v-model:value="formValue.twoSite" placeholder="层" class="form_site" clearable />
        </n-form-item>
        <n-form-item :label="bodyWidth < 600 ? ' ' : ''" path="threeSite">
          <n-input-number v-model:value="formValue.threeSite" placeholder="室" class="form_site" clearable />
        </n-form-item>
        <n-form-item>
          <n-button type="info" attr-type="button" @click="handleSearch" class="search_button">
            搜索
          </n-button>
        </n-form-item>
      </n-form>
    </div>
    <div class="table">
      <n-data-table :columns="bodyWidth < 600 ? phoneCloumns : columns" :data="indentsList" :pagination="false"
        :bordered="false" />
      <pagination :pageTotal="pageTotal" :pageConfig="pageConfig" :handleChangePage="handleChangePage" />
    </div>
    <n-drawer v-model:show="showDrawer" :width="bodyWidth < 600 ? '100%' : 500" placement="right"
      :on-after-leave="drawerClose" class="drawer">
      <n-drawer-content title="订单详情" :closable="true" class="drawer_content">
        <div v-for="item in detailData.list">
          <div class="row_good">
            <n-image width="50" height="50" :src="item.orderUrl[0]" />
            <div class="row_good_name">{{ item.orderName }}</div>
            <div class="row_good_price">{{ item.purchasePrice }}¥ × </div>
            <div :class="item.orderNum > 1 ? 'row_good_num_red' : 'row_good_num'">{{ item.orderNum }}</div>
          </div>
          <n-divider />
        </div>
        <div class="detail_content">
          <p>订单金额: {{ detailData.prices || "-" }}</p>
          <p>
            收货地址(楼栋):
            {{ detailData.detailedAddress }}
          </p>
          <p>收货人联系电话: {{ detailData.consigneePhone || "-" }}</p>
        </div>
        <n-card title="备注:">
          {{ detailData.remark || "无" }}
        </n-card>
      </n-drawer-content>
    </n-drawer>
  </div>
</template>

<style lang="scss" scoped>
.wrapper {
  overflow-y: scroll; //竖向滚动
  overflow-x: scroll; //横向滚动

  .search {
    height: 100px;
    padding: 20px;
    background-color: var(--BlockBgColor);
    transition: background-color 0.3s var(--n-bezier);
    display: flex;
    align-items: center;
    margin-bottom: 12px;

    @media screen and (max-width: 600px) {
      flex-direction: column;
      height: 400px;
    }

    .form_site {
      width: 100px;
    }

    .search_button {
      width: 130px;

      @media screen and (max-width: 600px) {
        width: 100%;
      }
    }
  }

  .table {
    padding: 20px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    background-color: var(--BlockBgColor);
    transition: background-color 0.3s var(--n-bezier);
    width: 100%;

    .table_action {
      height: 60px;
      display: flex;
      align-items: center;
    }
  }
}

.drawer {
  .drawer_content {
    .detail_content {
      display: flex;
      margin-bottom: 20px;
      justify-content: space-around;
    }

    .row_good {
      display: flex;
      align-items: center;

      // justify-content: space-around;
      .row_good_name {
        margin-left: 15px;
      }

      .row_good_price {
        margin-left: 15px;
      }

      .row_good_num {
        margin-left: 12px;
      }

      .row_good_num_red {
        margin-left: 12px;
        color: red;
        font-size: 19px;
        font-weight: 600;
      }
    }
  }
}
</style>
